import { parse } from 'yaml'
import * as path from 'path'
import * as fs from 'fs'
import * as dayjs from 'dayjs'

// 开发环境
export const isDev = process.env.NODE_ENV === 'development'

// 获取项目运行环境
export const getEnv = () => {
  return process.env.RUNNING_ENV
}

// 读取项目配置
export const getConfig = () => {
  const environment = getEnv() || 'prod'
  const yamlPath = path.join(process.cwd(), `/config/env.${environment}.yaml`)
  const file = fs.readFileSync(yamlPath, 'utf8')
  const config = parse(file)

  return config
}

/**
 * 获取年月日
 * @returns yyyyMMdd
 */
export function getDayjs(f = 'YYYYMMDD') {
  return dayjs().format(f)
}

// 判断文件夹是否存在，不存在则自动生成
export const checkDirAndCreate = (filePath: string) => {
  const pathArr = filePath.split('/')
  let checkPath = '.'
  let item: string

  for (item of pathArr) {
    checkPath += `/${item}`
    if (!fs.existsSync(checkPath)) {
      fs.mkdirSync(checkPath)
    }
  }
}

// 判断是否是图片文件
export const isImage = (mimeType: string) => {
  const image = ['gif', 'png', 'jpg', 'jpeg', 'bmp', 'webp']
  return image.filter((item) => item === mimeType).length > 0
}

// 获取仓库信息
export const getRepoInfo = (url, host = 'github.com') => {
  const regexPattern = `https://${host}/([^/]+)/([^/]+)`
  const regex = new RegExp(regexPattern)
  const matches = url.match(regex)

  return matches ? { username: matches[1], repoName: matches[2] } : { username: '', repoName: '' }
}
